import { app, BrowserWindow, ipcMain } from 'electron'
import { fileURLToPath } from 'node:url'
import path from 'node:path'

const __dirname = path.dirname(fileURLToPath(import.meta.url))

let mainWindow
let childWindows = new Set() // 用于管理子窗口

function createMainWindow() {
  mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      webSecurity: false,
      preload: path.join(__dirname, 'preload.js'),
      sandbox: false, // 禁用沙箱以便支持 ES 模块
    },
  })

  if (process.env.NODE_ENV === 'development') {
    mainWindow.loadURL('http://localhost:5173')
    mainWindow.webContents.openDevTools()
  } else {
    mainWindow.loadFile(path.join(__dirname, '../dist/index.html'))
  }

  // 窗口关闭时清理
  mainWindow.on('closed', () => {
    mainWindow = null
    // 关闭所有子窗口
    childWindows.forEach((win) => {
      if (!win.isDestroyed()) {
        win.close()
      }
    })
    childWindows.clear()
  })
}

// 创建新窗口的函数
function createChildWindow(options = {}) {
  // 确保 preload 路径正确
  const preloadPath =
    process.env.NODE_ENV === 'development'
      ? path.join(__dirname, 'preload.js')
      : path.join(process.resourcesPath, 'app.asar', 'electron', 'preload.js')
  const defaultOptions = {
    width: 800,
    height: 600,
    parent: mainWindow, // 设置为父窗口
    modal: false, // 是否为模态窗口
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      webSecurity: false,
      preload: preloadPath,
    },
  }

  const winOptions = { ...defaultOptions, ...options }
  const childWindow = new BrowserWindow(winOptions)

  // 如果有路由路径，构建完整的 URL
  if (options.route) {
    if (process.env.NODE_ENV === 'development') {
      // 开发环境：加载开发服务器 + 路由
      childWindow.loadURL(`http://localhost:5173${options.route}`)
    } else {
      // 生产环境：加载打包后的文件 + 路由哈希
      childWindow.loadFile('index.html')
      // 页面加载完成后设置路由
      childWindow.webContents.once('did-finish-load', () => {
        childWindow.webContents.send('set-route', options.route)
      })
    }
  } else if (options.url) {
    childWindow.loadURL(options.url)
  } else {
    childWindow.loadFile('index.html')
  }

  // 开发环境或指定打开开发者工具
  if (process.env.NODE_ENV === 'development' || options.openDevTools) {
    childWindow.webContents.openDevTools()
  }

  // 管理子窗口
  childWindows.add(childWindow)
  childWindow.on('closed', () => {
    childWindows.delete(childWindow)
  })

  // 正确的返回：返回可序列化的数据
  return {
    success: true,
    id: childWindow.id,
    title: options.title,
  }
}

// IPC 处理函数
function setupIpcHandlers() {
  // 打开新窗口
  ipcMain.handle('open-new-window', (event, options) => {
    return createChildWindow(options)
  })

  // 打开模态窗口
  ipcMain.handle('open-modal-window', (event, options) => {
    const modalOptions = {
      ...options,
      modal: true,
      parent: mainWindow,
    }
    return createChildWindow(modalOptions)
  })

  // 获取所有窗口信息
  ipcMain.handle('get-windows-info', () => {
    const windowsInfo = []
    if (mainWindow && !mainWindow.isDestroyed()) {
      windowsInfo.push({
        id: mainWindow.id,
        title: '主窗口',
        type: 'main',
      })
    }

    childWindows.forEach((win) => {
      if (!win.isDestroyed()) {
        windowsInfo.push({
          id: win.id,
          title: win.getTitle() || '子窗口',
          type: 'child',
        })
      }
    })

    return windowsInfo
  })

  // 关闭指定窗口
  ipcMain.handle('close-window', (event, windowId) => {
    if (mainWindow && mainWindow.id === windowId) {
      mainWindow.close()
      return true
    }

    for (const win of childWindows) {
      if (win.id === windowId && !win.isDestroyed()) {
        win.close()
        childWindows.delete(win)
        return true
      }
    }
    return false
  })

  // 添加路由设置的 IPC 处理
  ipcMain.handle('set-window-route', (event, route) => {
    const win = BrowserWindow.fromWebContents(event.sender)
    if (win) {
      win.webContents.send('set-route', route)
    }
  })

  // 调试相关 IPC 处理器
  ipcMain.handle('open-dev-tools', (event) => {
    const win = BrowserWindow.fromWebContents(event.sender)
    if (win && !win.isDestroyed()) {
      win.webContents.openDevTools()
      return { success: true }
    }
    return { success: false }
  })
  ipcMain.handle('close-dev-tools', (event) => {
    const win = BrowserWindow.fromWebContents(event.sender)
    if (win && !win.isDestroyed()) {
      win.webContents.closeDevTools()
      return { success: true }
    }
    return { success: false }
  })
  ipcMain.handle('toggle-dev-tools', (event) => {
    const win = BrowserWindow.fromWebContents(event.sender)
    if (win && !win.isDestroyed()) {
      win.webContents.toggleDevTools()
      return { success: true }
    }
    return { success: false }
  })
  ipcMain.handle('open-dev-tools-for-window', (event, windowId) => {
    const win = BrowserWindow.fromId(windowId)
    if (win && !win.isDestroyed()) {
      win.webContents.openDevTools()
      return { success: true }
    }
    return { success: false }
  })
  ipcMain.handle('get-debug-info', (event) => {
    const win = BrowserWindow.fromWebContents(event.sender)
    return {
      environment: 'electron',
      electronVersion: process.versions.electron,
      chromeVersion: process.versions.chrome,
      nodeVersion: process.versions.node,
      platform: process.platform,
      windowId: win ? win.id : null,
      devToolsOpened: win ? win.webContents.isDevToolsOpened() : false,
      windowCount: BrowserWindow.getAllWindows().length,
    }
  })
}

app.whenReady().then(() => {
  createMainWindow()
  setupIpcHandlers()
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createMainWindow()
  }
})
